/**
 * 采购退货出库 - 主界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.PurchaseRej.PRMainForm", {
  extend: "PSI.AFX.Form.MainForm",

  config: {
    permission: null
  },

  /**
   * @override
   */
  initComponent() {
    const me = this;

    PCL.apply(me, {
      items: [{
        tbar: me.getToolbarCmp(),
        id: me.buildId(me, "panelQueryCmp"),
        region: "north",
        height: 125,
        layout: "fit",
        header: false,
        border: 0,
        collapsible: true,
        collapseMode: "mini",
        layout: {
          type: "table",
          columns: 5
        },
        bodyCls: "PSI-Query-Panel",
        items: me.getQueryCmp()
      }, {
        region: "center",
        layout: "border",
        ...PSI.Const.BODY_PADDING,
        border: 0,
        items: [{
          region: "center",
          layout: "fit",
          border: 0,
          items: [me.getMainGrid()]
        }, {
          region: "south",
          layout: "border",
          height: "60%",
          split: true,
          collapsible: true,
          header: false,
          border: 0,
          items: [{
            region: "north",
            bodyStyle: "border-width:1px 1px 0px 1px",
            height: 40,
            layout: {
              type: "table",
              columns: 5
            },
            bodyPadding: 10,
            items: me.getBillSummaryCmp()
          }, {
            region: "center",
            border: 0,
            layout: "fit",
            items: me.getDetailGrid()
          }]
        }]
      }]
    });

    me.callParent(arguments);

    me._keyMapMain = PCL.create("PCL.util.KeyMap", PCL.getBody(), [{
      key: "N",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        // 判断权限
        if (me.getPermission().add != "1") {
          return;
        }

        me._onAddBill.apply(me, []);
      },
      scope: me
    }, {
      key: "Q",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }
        me.editQueryRef.focus();
      },
      scope: me
    }, {
      key: "H",
      ctrl: false,
      shift: false,
      alt: true,
      fn() {
        if (PSI.Const.msgBoxShowing) {
          return;
        }

        const panel = PCL.getCmp(me.buildId(me, "panelQueryCmp"));
        if (panel.getCollapsed()) {
          panel.expand();
        } else {
          panel.collapse();
        };
      },
      scope: me
    },
    ]);

    me.editQueryBillStatus = PCL.getCmp(me.buildId(me, "editQueryBillStatus"));
    me.editQueryRef = PCL.getCmp(me.buildId(me, "editQueryRef"));
    me.editQueryFromDT = PCL.getCmp(me.buildId(me, "editQueryFromDT"));
    me.editQueryToDT = PCL.getCmp(me.buildId(me, "editQueryToDT"));
    me.editQuerySupplier = PCL.getCmp(me.buildId(me, "editQuerySupplier"));
    me.editQueryWarehouse = PCL.getCmp(me.buildId(me, "editQueryWarehouse"));
    me.editQueryReceivingType = PCL.getCmp(me.buildId(me, "editQueryReceivingType"));
    me.editQueryGoods = PCL.getCmp(me.buildId(me, "editQueryGoods"));

    me.editSummaryRef = PCL.getCmp(me.buildId(me, "editSummaryRef"));
    me.editSummaryWarehouse = PCL.getCmp(me.buildId(me, "editSummaryWarehouse"));

    me.buttonEdit = PCL.getCmp(me.buildId(me, "buttonEdit"));
    me.buttonDelete = PCL.getCmp(me.buildId(me, "buttonDelete"));
    me.buttonCommit = PCL.getCmp(me.buildId(me, "buttonCommit"));

    // AFX: 查询控件input List
    me.__editorList = [
      me.editQueryBillStatus,
      me.editQueryRef,
      me.editQueryFromDT,
      me.editQueryToDT,
      me.editQuerySupplier,
      me.editQueryWarehouse,
      me.editQueryReceivingType,
      me.editQueryGoods];

    me.refreshMainGrid();
  },

  /**
   * @private
   */
  getToolbarCmp() {
    const me = this;

    let result = [];
    let list = [];

    // 新建
    if (me.getPermission().add == "1") {
      result.push({
        iconCls: "PSI-tb-new",
        text: "新建采购退货出库单 <span class='PSI-shortcut-DS'>Alt + N</span>",
        tooltip: "快捷键：Alt + N",
        ...PSI.Const.BTN_STYLE,
        id: "buttonAdd",
        scope: me,
        handler: me._onAddBill
      });
    }

    // 变更
    list = [];
    if (me.getPermission().edit == "1") {
      list.push({
        text: "编辑采购退货出库单",
        id: me.buildId(me, "buttonEdit"),
        scope: me,
        handler: me._onEditBill
      });
    }
    if (me.getPermission().del == "1") {
      list.push({
        text: "删除采购退货出库单",
        id: me.buildId(me, "buttonDelete"),
        hidden: me.getPermission().del == "0",
        scope: me,
        handler: me._onDeleteBill
      });
    }
    if (list.length > 0) {
      if (result.length > 0) {
        result.push("-");
      }

      result.push({
        text: "变更",
        ...PSI.Const.BTN_STYLE,
        menu: list
      });
    }

    // 提交
    if (me.getPermission().commit == "1") {
      if (result.length > 0) {
        result.push("-");
      }

      result.push({
        iconCls: "PSI-tb-commit",
        text: "提交出库",
        ...PSI.Const.BTN_STYLE,
        id: me.buildId(me, "buttonCommit"),
        scope: me,
        handler: me._onCommit
      });
    }

    // 导出
    list = [];
    if (me.getPermission().genPDF == "1") {
      list.push({
        text: "单据生成pdf",
        id: "buttonPDF",
        iconCls: "PSI-button-pdf",
        scope: me,
        handler: me._onPDF
      });
    }
    if (list.length > 0) {
      if (result.length > 0) {
        result.push("-");
      }

      result.push({
        text: "导出",
        ...PSI.Const.BTN_STYLE,
        menu: list
      });
    }

    // 打印
    list = [];
    if (me.getPermission().print == "1") {
      if (result.length > 0) {
        result.push("-");
      }

      list.push({
        text: "打印预览",
        iconCls: "PSI-button-print-preview",
        scope: me,
        handler: me._onPrintPreview
      }, {
        text: "直接打印",
        iconCls: "PSI-button-print",
        scope: me,
        handler: me._onPrint
      });

      result.push({
        text: "打印",
        ...PSI.Const.BTN_STYLE,
        menu: list
      });
    }

    // 指南
    // 关闭
    if (result.length > 0) {
      result.push("-");
    }
    result.push({
      iconCls: "PSI-tb-help",
      text: "指南",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        window.open(me.URL("Home/Help/index?t=prbill"));
      }
    }, "-", {
      iconCls: "PSI-tb-close",
      text: "关闭",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.focus();
        me.closeWindow();
      }
    });

    result = result.concat(me.getPagination()).concat(me.getShortcutCmp());

    return result;
  },

  /**
   * 快捷访问
   * 
   * @private
   */
  getShortcutCmp() {
    return ["|", " ",
      {
        cls: "PSI-Shortcut-Cmp",
        labelWidth: 0,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield",
        width: 90
      }
    ];
  },

  /**
   * @private
   */
  getQueryCmp() {
    const me = this;
    return [{
      xtype: "container",
      height: 26,
      html: `<h2 style='margin-left:20px;margin-top:32px;color:#595959;display:inline-block'>采购退货出库</h2>
            &nbsp;&nbsp;<span style='color:#8c8c8c'>单据列表</span>
            <div style='float:right;display:inline-block;margin:10px 0px 0px 20px;border-left:1px solid #e5e6e8;height:70px'>&nbsp;</div>
            `
    }, {
      id: me.buildId(me, "editQueryBillStatus"),
      xtype: "combo",
      queryMode: "local",
      editable: false,
      valueField: "id",
      labelWidth: 60,
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "状态",
      margin: "5, 0, 0, 0",
      store: PCL.create("PCL.data.ArrayStore", {
        fields: ["id", "text"],
        data: [[-1, "全部"], [0, "待出库"], [1000, "已出库"]]
      }),
      value: -1,
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryRef"),
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "单号 <span class='PSI-shortcut-DS'>Alt + Q</span>",
      labelWidth: 90,
      margin: "5, 0, 0, 0",
      xtype: "textfield",
      width: 220,
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryFromDT"),
      xtype: "datefield",
      margin: "5, 0, 0, 0",
      format: "Y-m-d",
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "业务日期（起）",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryToDT"),
      xtype: "datefield",
      margin: "5, 0, 0, 0",
      format: "Y-m-d",
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "业务日期（止）",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, { xtype: "container" }, {
      id: me.buildId(me, "editQuerySupplier"),
      xtype: "psi_supplierfield",
      showModal: true,
      labelAlign: "right",
      labelSeparator: "",
      margin: "5, 0, 0, 0",
      labelWidth: 60,
      fieldLabel: "供应商",
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryWarehouse"),
      xtype: "psi_warehousefield",
      showModal: true,
      labelAlign: "right",
      labelSeparator: "",
      labelWidth: 60,
      margin: "5, 0, 0, 0",
      fieldLabel: "仓库",
      width: 220,
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    }, {
      id: me.buildId(me, "editQueryReceivingType"),
      margin: "5, 0, 0, 0",
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "收款方式",
      xtype: "combo",
      queryMode: "local",
      editable: false,
      valueField: "id",
      store: PCL.create("PCL.data.ArrayStore", {
        fields: ["id", "text"],
        data: [[-1, "全部"], [0, "记应收账款"], [1, "现金收款"]]
      }),
      value: -1,
      listeners: {
        specialkey: {
          fn: me.__onEditSpecialKey,
          scope: me
        }
      }
    },
    {
      xtype: "container",
      colspan: 2,
      items: [{
        xtype: "button",
        text: "查询",
        cls: "PSI-Query-btn1",
        width: 100,
        height: 26,
        margin: "5 0 0 10",
        handler: me._onQuery,
        scope: me
      }, {
        xtype: "button",
        text: "清空查询条件",
        cls: "PSI-Query-btn2",
        width: 100,
        height: 26,
        margin: "5, 0, 0, 10",
        handler: me._onClearQuery,
        scope: me
      }, {
        xtype: "button",
        text: "隐藏工具栏 <span class='PSI-shortcut-DS'>Alt + H</span>",
        cls: "PSI-Query-btn3",
        width: 140,
        height: 26,
        iconCls: "PSI-button-hide",
        margin: "5 0 0 20",
        handler() {
          PCL.getCmp(me.buildId(me, "panelQueryCmp")).collapse();
        },
        scope: me
      }]
    }, { xtype: "container" }, {
      id: me.buildId(me, "editQueryGoods"),
      labelAlign: "right",
      labelSeparator: "",
      fieldLabel: "物料",
      labelWidth: 60,
      margin: "5, 0, 0, 0",
      xtype: "psi_goodsfield",
      showModal: true,
      listeners: {
        specialkey: {
          fn: me.__onLastEditSpecialKey,
          scope: me
        }
      }
    }];
  },

  /**
   * @private
   */
  getBillSummaryCmp() {
    const me = this;

    const fieldProps = {
      xtype: "textfield",
      readOnly: true,
      labelSeparator: "",
      labelAlign: "right",
    };
    return [{
      xtype: "container",
      height: 22,
      html: "<span style='padding:0px;margin:0px 0px 0px -5px;border-left: 5px solid #9254de'></span>",
    }, {
      id: me.buildId(me, "editSummaryRef"),
      fieldLabel: "单号",
      labelWidth: 30,
      value: "",
      ...fieldProps,
    }, {
      id: me.buildId(me, "editSummaryWarehouse"),
      fieldLabel: "出库仓库",
      labelWidth: 70,
      value: "",
      ...fieldProps,
    }];
  },

  /**
   * @private
   */
  resetSummaryInput() {
    const me = this;
    me.editSummaryRef.setValue("");
    me.editSummaryWarehouse.setValue("");
  },

  /**
   * @private
   */
  refreshMainGrid(id) {
    const me = this;

    me.resetSummaryInput();

    me.buttonEdit?.setDisabled(true);
    me.buttonDelete?.setDisabled(true);
    me.buttonCommit?.setDisabled(true);

    const gridDetail = me.getDetailGrid();
    gridDetail.getStore().removeAll();
    PCL.getCmp(me.buildId(me, "pagingToobar")).doRefresh();
    me.__lastId = id;
  },

  /**
   * 新建采购退货出库单
   * 
   * @private
   */
  _onAddBill() {
    const me = this;
    const form = PCL.create("PSI.SLN0001.PurchaseRej.PREditForm", {
      parentForm: me
    });
    form.show();
  },

  /**
   * 编辑采购退货出库单
   * 
   * @private
   */
  _onEditBill() {
    const me = this;
    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要编辑的采购退货出库单");
      return;
    }

    const bill = item[0];
    const form = PCL.create("PSI.SLN0001.PurchaseRej.PREditForm", {
      parentForm: me,
      entity: bill
    });
    form.show();
  },

  /**
   * 删除采购退货出库单
   * 
   * @private
   */
  _onDeleteBill() {
    const me = this;

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要删除的采购退货出库单");
      return;
    }
    const bill = item[0];

    if (bill.get("billStatus") == "已出库") {
      me.showInfo("当前采购退货出库单已经提交出库，不能删除");
      return;
    }

    const info = `请确认是否删除采购退货出库单: <span style='color:red'>${bill.get("ref")}</span>`;

    me.confirm(info, () => {
      const el = PCL.getBody();
      el.mask("正在删除中...");
      me.ajax({
        url: me.URL("SLN0001/PurchaseRej/deletePRBill"),
        params: {
          id: bill.get("id")
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.refreshMainGrid();
              me.tip("成功完成删除操作", true);
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      });
    });
  },

  /**
   * 提交采购退货出库单
   * 
   * @private
   */
  _onCommit() {
    const me = this;

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择要提交的采购退货出库单");
      return;
    }

    const bill = item[0];

    if (bill.get("billStatus") == "已出库") {
      me.showInfo("当前采购退货出库单已经提交出库，不能再次提交");
      return;
    }

    const info = `请确认是否提交单号为: <span style='color:red'>${bill.get("ref")}</span> 的采购退货出库单?`;
    me.confirm(info, () => {
      const el = PCL.getBody();
      el.mask("正在提交中...");
      me.ajax({
        url: me.URL("SLN0001/PurchaseRej/commitPRBill"),
        params: {
          id: bill.get("id")
        },
        callback(options, success, response) {
          el.unmask();

          if (success) {
            const data = me.decodeJSON(response.responseText);
            if (data.success) {
              me.refreshMainGrid(data.id);
              me.tip("成功完成提交操作", true);
            } else {
              me.showInfo(data.msg);
            }
          } else {
            me.showInfo("网络错误");
          }
        }
      });
    });
  },

  /**
   * @private
   */
  getPagination() {
    const me = this;
    const store = me.getMainGrid().getStore();
    const result = ["->", {
      id: me.buildId(me, "pagingToobar"),
      xtype: "pagingtoolbar",
      cls: "PSI-Pagination",
      border: 0,
      store: store
    }, "-", {
        xtype: "displayfield",
        value: "每页显示"
      }, {
        id: me.buildId(me, "comboCountPerPage"),
        xtype: "combobox",
        cls: "PSI-Pagination",
        editable: false,
        width: 60,
        store: PCL.create("PCL.data.ArrayStore", {
          fields: ["text"],
          data: [["20"], ["50"], ["100"],
          ["300"], ["1000"]]
        }),
        value: 20,
        listeners: {
          change: {
            fn() {
              store.pageSize = PCL.getCmp(me.buildId(me, "comboCountPerPage")).getValue();
              store.currentPage = 1;
              PCL.getCmp(me.buildId(me, "pagingToobar")).doRefresh();
            },
            scope: me
          }
        }
      }, {
        xtype: "displayfield",
        value: "张单据"
      }];

    return result;
  },

  /**
   * @private
   */
  getMainGrid() {
    const me = this;
    if (me._mainGrid) {
      return me._mainGrid;
    }

    const modelName = me.buildModelName(me, "PRBill");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "ref", "bizDT", "warehouseName",
        "supplierName", "inputUserName", "bizUserName",
        "billStatus", "rejMoney", "dateCreated",
        "receivingType", "billMemo", "tax", "rejMoneyWithTax", "pwRef"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: [],
      pageSize: 20,
      proxy: {
        type: "ajax",
        actionMethods: {
          read: "POST"
        },
        url: me.URL("SLN0001/PurchaseRej/prbillList"),
        reader: {
          root: 'dataList',
          totalProperty: 'totalCount'
        }
      }
    });
    store.on("beforeload", () => {
      store.proxy.extraParams = me.getQueryParam();
    });
    store.on("load", (e, records, successful) => {
      if (successful) {
        me.gotoMainGridRecord(me.__lastId);
      }
    });

    me._mainGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-FC",
      viewConfig: {
        enableTextSelection: true
      },
      border: 1,
      columnLines: true,
      columns: [{
        xtype: "rownumberer",
        text: "#",
        width: 40
      }, {
        header: "状态",
        dataIndex: "billStatus",
        menuDisabled: true,
        sortable: false,
        width: 60,
        renderer(value) {
          return value == "待出库"
            ? `<span style='color:red'>${value}</span>`
            : value;
        }
      }, {
        header: "退货出库单号",
        dataIndex: "ref",
        width: 120,
        menuDisabled: true,
        sortable: false
      }, {
        header: "采购入库单号",
        dataIndex: "pwRef",
        width: 120,
        menuDisabled: true,
        sortable: false,
        renderer(value, md, record) {
          return `<a href='${PSI.Const.BASE_URL}SLN0001/Bill/viewIndex?fid=2007&refType=${encodeURIComponent("采购入库")}&ref=${encodeURIComponent(value)}' 
                    target='_blank'>${value}
                  </a>`;
        }
      }, {
        header: "业务日期",
        dataIndex: "bizDT",
        menuDisabled: true,
        sortable: false,
        width: 90,
        align: "center"
      }, {
        header: "供应商",
        dataIndex: "supplierName",
        menuDisabled: true,
        sortable: false,
        width: 300
      }, {
        header: "收款方式",
        dataIndex: "receivingType",
        menuDisabled: true,
        sortable: false,
        width: 90,
        renderer(value) {
          if (value == 0) {
            return "记应收账款";
          } else if (value == 1) {
            return "现金收款";
          } else {
            return "";
          }
        }
      }, {
        header: "出库仓库",
        dataIndex: "warehouseName",
        menuDisabled: true,
        sortable: false,
        width: 150
      }, {
        header: "退货金额(不含税)",
        dataIndex: "rejMoney",
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 120
      }, {
        header: "税金(红字)",
        dataIndex: "tax",
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 90
      }, {
        header: "退货金额(含税)",
        dataIndex: "rejMoneyWithTax",
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn",
        width: 120
      }, {
        header: "业务员",
        dataIndex: "bizUserName",
        menuDisabled: true,
        sortable: false
      }, {
        header: "制单人",
        dataIndex: "inputUserName",
        menuDisabled: true,
        sortable: false
      }, {
        header: "制单时间",
        dataIndex: "dateCreated",
        width: 150,
        menuDisabled: true,
        sortable: false
      }, {
        header: "备注",
        dataIndex: "billMemo",
        width: 300,
        menuDisabled: true,
        sortable: false
      }],
      listeners: {
        select: {
          fn: me._onMainGridSelect,
          scope: me
        },
        itemdblclick: {
          fn: me.getPermission().edit == "1"
            ? me._onEditBill
            : PCL.emptyFn,
          scope: me
        }
      },
      store: store,
    });

    return me._mainGrid;
  },

  /**
   * @private
   */
  getDetailGrid() {
    const me = this;
    if (me._detailGrid) {
      return me._detailGrid;
    }

    const modelName = me.buildModelName(me, "PRBillDetail");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "goodsCode", "goodsName", "goodsSpec",
        "unitName", "rejCount", "rejPrice", "rejMoney",
        "memo", "tax", "taxRate", "rejPriceWithTax", "rejMoneyWithTax"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: []
    });

    me._detailGrid = PCL.create("PCL.grid.Panel", {
      cls: "PSI-HL",
      viewConfig: {
        enableTextSelection: true
      },
      columnLines: true,
      columns: [PCL.create("PCL.grid.RowNumberer", {
        text: "#",
        width: 40
      }), {
        header: "物料编码",
        dataIndex: "goodsCode",
        menuDisabled: true,
        sortable: false
      }, {
        header: "品名/规格型号",
        dataIndex: "goodsName",
        menuDisabled: true,
        sortable: false,
        width: 330,
        renderer(value, metaData, record) {
          return record.get("goodsName") + " " + record.get("goodsSpec");
        }
      }, {
        header: "退货数量",
        dataIndex: "rejCount",
        menuDisabled: true,
        sortable: false,
        align: "right",
        width: 80
      }, {
        header: "单位",
        dataIndex: "unitName",
        menuDisabled: true,
        sortable: false,
        width: 50,
        align: "center"
      }, {
        header: "退货单价(不含税)",
        dataIndex: "rejPrice",
        menuDisabled: true,
        sortable: false,
        align: "right",
        width: 120,
        xtype: "numbercolumn"
      }, {
        header: "退货金额(不含税)",
        dataIndex: "rejMoney",
        menuDisabled: true,
        sortable: false,
        align: "right",
        width: 120,
        xtype: "numbercolumn"
      }, {
        header: "税率(%)",
        dataIndex: "taxRate",
        menuDisabled: true,
        sortable: false,
        align: "right",
        width: 60,
        xtype: "numbercolumn",
        format: "#"
      }, {
        header: "税金(红字)",
        dataIndex: "tax",
        menuDisabled: true,
        sortable: false,
        align: "right",
        width: 100,
        xtype: "numbercolumn"
      }, {
        header: "退货单价(含税)",
        dataIndex: "rejPriceWithTax",
        menuDisabled: true,
        sortable: false,
        align: "right",
        width: 120,
        xtype: "numbercolumn"
      }, {
        header: "退货金额(含税)",
        dataIndex: "rejMoneyWithTax",
        menuDisabled: true,
        sortable: false,
        align: "right",
        width: 120,
        xtype: "numbercolumn"
      }, {
        header: "备注",
        dataIndex: "memo",
        menuDisabled: true,
        sortable: false,
        width: 300
      }],
      store: store
    });

    return me._detailGrid;
  },

  /**
   * @private
   */
  _onMainGridSelect() {
    const me = this;
    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.buttonEdit?.setDisabled(true);
      me.buttonDelete?.setDisabled(true);
      me.buttonCommit?.setDisabled(true);

      return;
    }
    const bill = item[0];

    const commited = bill.get("billStatus") == "已出库";
    me.buttonDelete?.setDisabled(commited);
    me.buttonCommit?.setDisabled(commited);

    const buttonEdit = me.buttonEdit;
    buttonEdit?.setDisabled(false);
    if (commited) {
      buttonEdit?.setText("查看采购退货出库单");
    } else {
      buttonEdit?.setText("编辑采购退货出库单");
    }

    me.editSummaryRef.setValue(bill.get("ref"));
    me.editSummaryWarehouse.setValue(bill.get("warehouseName"));

    me.refreshDetailGrid();
  },

  /**
   * @private
   */
  refreshDetailGrid(id) {
    const me = this;
    let grid = me.getMainGrid();
    const item = grid.getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      return;
    }

    const bill = item[0];

    grid = me.getDetailGrid();
    const el = grid.getEl();
    el?.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/PurchaseRej/prBillDetailList"),
      params: {
        id: bill.get("id")
      },
      callback(options, success, response) {
        const store = grid.getStore();

        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);

          if (store.getCount() > 0) {
            if (id) {
              const r = store.findExact("id", id);
              if (r != -1) {
                grid.getSelectionModel().select(r);
              }
            }
          }
        }

        el?.unmask();
      }
    });
  },

  /**
   * @private
   */
  gotoMainGridRecord(id) {
    const me = this;
    const grid = me.getMainGrid();
    grid.getSelectionModel().deselectAll();
    const store = grid.getStore();
    if (id) {
      const r = store.findExact("id", id);
      if (r != -1) {
        grid.getSelectionModel().select(r);
      } else {
        grid.getSelectionModel().select(0);
      }
    } else {
      grid.getSelectionModel().select(0);
    }
  },

  /**
   * @private
   */
  _onQuery() {
    const me = this;

    me.getMainGrid().getStore().currentPage = 1;
    me.refreshMainGrid();
  },

  /**
   * @private
   */
  _onClearQuery() {
    const me = this;

    me.editQueryBillStatus.setValue(-1);
    me.editQueryRef.setValue(null);
    me.editQueryFromDT.setValue(null);
    me.editQueryToDT.setValue(null);
    me.editQuerySupplier.clearIdValue();
    me.editQueryWarehouse.clearIdValue();
    me.editQueryReceivingType.setValue(-1);
    me.editQueryGoods.clearIdValue();

    me._onQuery();
  },

  /**
   * @private
   */
  getQueryParam() {
    const me = this;

    const result = {
      billStatus: me.editQueryBillStatus.getValue()
    };

    const ref = me.editQueryRef.getValue();
    if (ref) {
      result.ref = ref;
    }

    const supplierId = me.editQuerySupplier.getIdValue();
    if (supplierId) {
      result.supplierId = supplierId;
    }

    const warehouseId = me.editQueryWarehouse.getIdValue();
    if (warehouseId) {
      result.warehouseId = warehouseId;
    }

    const fromDT = me.editQueryFromDT.getValue();
    if (fromDT) {
      result.fromDT = PCL.Date.format(fromDT, "Y-m-d");
    }

    const toDT = me.editQueryToDT.getValue();
    if (toDT) {
      result.toDT = PCL.Date.format(toDT, "Y-m-d");
    }

    const receivingType = me.editQueryReceivingType.getValue();
    result.receivingType = receivingType;

    const goodsId = me.editQueryGoods.getIdValue();
    if (goodsId) {
      result.goodsId = goodsId;
    }

    return result;
  },

  /**
   * @private
   */
  _onPDF() {
    const me = this;

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择要生成pdf文件的采购退货出库单");
      return;
    }

    const bill = item[0];

    const url = PSI.Const.BASE_URL + "SLN0001/PurchaseRej/prBillPdf?ref="
      + bill.get("ref");
    window.open(url);

    me.focus();
  },

  /**
   * @private
   */
  _onPrintPreview() {
    const me = this;

    if (PSI.Const.ENABLE_LODOP != "1") {
      me.showInfo("请先在业务设置模块中启用Lodop打印");
      return;
    }

    const lodop = getLodop();
    if (!lodop) {
      me.showInfo("没有安装Lodop控件，无法打印");
      return;
    }

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择要打印的采购退货出库单");
      return;
    }

    const bill = item[0];

    const el = PCL.getBody();
    el.mask("数据加载中...");
    const r = {
      url: me.URL("SLN0001/PurchaseRej/genPRBillPrintPage"),
      params: {
        id: bill.get("id")
      },
      callback(options, success, response) {
        el.unmask();

        if (success) {
          const data = response.responseText;
          me.previewPRBill(bill.get("ref"), data);
        }
      }
    };
    me.ajax(r);
  },

  PRINT_PAGE_WIDTH: "200mm",
  PRINT_PAGE_HEIGHT: "95mm",

  /**
   * @private
   */
  previewPRBill(ref, data) {
    const me = this;

    const lodop = getLodop();
    if (!lodop) {
      me.showInfo("Lodop打印控件没有正确安装");
      return;
    }

    lodop.PRINT_INIT("采购退货出库单" + ref);
    lodop.SET_PRINT_PAGESIZE(1, me.PRINT_PAGE_WIDTH, me.PRINT_PAGE_HEIGHT,
      "");
    lodop.ADD_PRINT_HTM("0mm", "0mm", "100%", "100%", data);
    lodop.PREVIEW("_blank");
  },

  /**
   * @private
   */
  _onPrint() {
    const me = this;

    if (PSI.Const.ENABLE_LODOP != "1") {
      me.showInfo("请先在业务设置模块中启用Lodop打印");
      return;
    }

    const lodop = getLodop();
    if (!lodop) {
      me.showInfo("没有安装Lodop控件，无法打印");
      return;
    }

    const item = me.getMainGrid().getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("没有选择要打印的采购退货出库单");
      return;
    }

    const bill = item[0];

    const el = PCL.getBody();
    el.mask("数据加载中...");
    const r = {
      url: PSI.Const.BASE_URL + "SLN0001/PurchaseRej/genPRBillPrintPage",
      params: {
        id: bill.get("id")
      },
      callback(options, success, response) {
        el.unmask();

        if (success) {
          const data = response.responseText;
          me.printPRBill(bill.get("ref"), data);
        }
      }
    };
    me.ajax(r);
  },

  /**
   * @private
   */
  printPRBill(ref, data) {
    const me = this;

    const lodop = getLodop();
    if (!lodop) {
      me.showInfo("Lodop打印控件没有正确安装");
      return;
    }

    lodop.PRINT_INIT("采购入库单" + ref);
    lodop.SET_PRINT_PAGESIZE(1, me.PRINT_PAGE_WIDTH, me.PRINT_PAGE_HEIGHT,
      "");
    lodop.ADD_PRINT_HTM("0mm", "0mm", "100%", "100%", data);
    lodop.PRINT();
  }
});
